package cn.usersmsg.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.usersmsg.biz.IUserBiz;
import cn.usersmsg.biz.UserBizIpml;
import cn.usersmsg.model.User;

public class UserLogin extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String username = request.getParameter("username");
		String userpwd = request.getParameter("userpwd");
		String validity = request.getParameter("validity");
		int time =0;
		if (validity!=null) {
			time = Integer.parseInt(validity);
		}
		IUserBiz iub = new UserBizIpml();
		User user = iub.userLogin(username, userpwd);
		if (user!=null) {
			HttpSession session = request.getSession();
			session.setAttribute("user", user);
			Cookie cookie = new Cookie("username", username);
			cookie.setMaxAge(time*60*60*24);
			response.addCookie(cookie);
			request.getRequestDispatcher("index.jsp").forward(request, response);
		}else{
			response.sendRedirect("home.jsp");
		}
	}
	
}
